package com.learning.crpc.consummer;

import com.learning.crpc.model.CrpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @program: diy_rpc
 * @description:
 * @author: CaoYong
 * @create: 2021-07-01 18:26
 **/
public class NettyConsumerHandler extends SimpleChannelInboundHandler<CrpcResponse> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, CrpcResponse crpcResponse) throws Exception {
        System.out.println("收到一个响应：" + crpcResponse);

        if(crpcResponse.getCode() == 400) {
            throw new Exception(crpcResponse.getContent().toString());
        }

        CrpcConnection crpcConnection = NettyConsumerClient.connectionInfo.get(channelHandlerContext.channel().remoteAddress());
        crpcConnection.complete(crpcResponse);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        NettyConsumerClient.connectionInfo.remove(ctx.channel().remoteAddress());
    }
}
